package com.yamaha.bikedesalon;

import java.net.SocketTimeoutException;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;

public abstract class MyAsyncHttpResponseHandler
		extends
			AsyncHttpResponseHandler {

	private final String name;
	private final Context context;

	public MyAsyncHttpResponseHandler(final String name, final Context context) {
		this.name = name;
		this.context = context;
	}

	@Override
	public void onStart() {
		super.onStart();

		LogUtil.i("Call WebService", "WebService : " + name + ", Started...");
	}

	@Override
	public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
		super.onSuccess(statusCode, headers, responseBody);

		try {

			final String res = new String(responseBody, "UTF-8");
			LogUtil.i("Call WebService", "WebService : " + name + ", Success...");
			LogUtil.i("Call WebService", "Response : " + res);

			final JSONObject object = new JSONObject(res);

			if (object.getBoolean("success")) {
				onAsyncSuccess(object.get("message"));
			} else {
				final String msg = object.getString("message");
				Toast.makeText(this.context, msg, Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			LogUtil.e(this.context, "Call WebService", e.getMessage(), e);
		}
	}
	protected abstract void onAsyncSuccess(final Object res)
			throws JSONException;

	@Override
	public void onRetry() {
		super.onRetry();

		LogUtil.v("Call WebService", "Retring Request....");
	}

	@Override
	public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] responseBody, java.lang.Throwable error) {
		super.onFailure(statusCode, headers, responseBody, error);

		LogUtil.e("Call WebService", "WebService : " + name + ", Failure", error);
		LogUtil.w("Call WebService", error.getLocalizedMessage());

		if (error instanceof SocketTimeoutException) {
			Toast.makeText(this.context, "No Connection, Please try again.", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this.context, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onFinish() {
		super.onFinish();

		LogUtil.i("Call WebService", "WebService : " + name + ", Finished.");
	}

}
